import SwiftUI
import SwiftData

// SellNewPage
// 转一转新增页面

struct SellNewPage: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var loginInfo: [LoginInfo]
    
    @Environment(\.dismiss) private var dismiss
    
    @State private var bookEANCode: String = ""
    
    @State private var bookNameInput: String = ""
    @State private var bookTagInput: String = ""
    @State private var bookrequirePrice: String = ""
    
    @State private var bookAuthorInput: String = ""
    @State private var bookCourseInput: String = ""
    @State private var bookDescriptionInput: String = ""

    @State private var photoPickerShow: Bool = false
    @State private var imageIdArray = [String]()

    @StateObject private var codeFetecher = BookCodeFetecher()
    @StateObject private var addBookRequest = BookAddBookRequester()
    @StateObject private var modifyBookRequester = BookModifyBookRequester()
    @StateObject private var modifyStateRequester = BookModifyStateRequester()
    @StateObject private var lazyDeleteImageRequester = BookLazyDeleteImageRequester()
    
    var body: some View {
        ScrollView {
            if (addBookRequest.publishedResult.status) {
                List {
                    Section {
                        NavigationLink {
                            EANScannerPage(lastEANCode: $bookEANCode)
                        } label: {
                            Text("扫码书籍条形码快速填写")
                        }
                    }
                    
                    Section {
                        HStack {
                            Text("*")
                                .foregroundColor(.red)
                            Text("书籍名称")
                            Spacer()
                            TextField("书籍名称", text: $bookNameInput)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.trailing)
                        }
                        
                        HStack {
                            Text("*")
                                .foregroundColor(.red)
                            Text("标签")
                            Spacer()
                            TextField("如：“全新”、“有笔记”", text: $bookTagInput)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.trailing)
                        }
                        
                        HStack {
                            Text("*")
                                .foregroundColor(.red)
                            Text("期望价格")
                            Spacer()
                            TextField("¥", text: $bookrequirePrice)
                                .keyboardType(.decimalPad)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.trailing)
                                .onChange(of: bookrequirePrice) {
                                    if let first = bookrequirePrice.first {
                                        if(first != "¥") {
                                            bookrequirePrice = "¥" + bookrequirePrice
                                        }
                                    }
                                }
                        }
                        
                        HStack {
                            Text("作者")
                            Spacer()
                            TextField("作者", text: $bookAuthorInput)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.trailing)
                        }
                        
                        HStack {
                            Text("使用课程")
                            Spacer()
                            TextField("使用课程", text: $bookCourseInput)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.trailing)
                        }
                    }
                    .onChange(of: bookEANCode) {
                        codeFetecher.fetch(code: bookEANCode)
                    }
                    .onChange(of: codeFetecher.publishedResult.status) {
                        if(codeFetecher.publishedResult.status) {
                            bookNameInput = codeFetecher.publishedResult.bookName
                            bookAuthorInput = codeFetecher.publishedResult.author
                            bookCourseInput = codeFetecher.publishedResult.course
                        }
                    }
                    
                    Section {
                        if imageIdArray.count <= 8 {
                            Button{
                                withAnimation {
                                    photoPickerShow.toggle()
                                }
                            } label: {
                                Text("添加图片")
                            }
                        }
                        
                        HStack(alignment: .center) {
                            Text("简介")
                            
                            TextEditor(text: $bookDescriptionInput)
                                .frame(minHeight: 48)
                        }
                    }
                }
                .containerRelativeFrame(.vertical) {
                    length, axis in
                    if axis == .vertical {
                        return length * 0.8
                    } else {
                        return length
                    }
                }
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3)) {
                    ForEach(imageIdArray, id:\.self) { imageId in
                        let imageURL = URL(string: "http://62.234.45.120:1230/storage/bookImage/" + imageId + ".jpeg")!
                        GeometryReader { geo in
                            NavigationLink(destination:PhotoDetail(imageURL: imageURL)) {
                                AsyncImage(url: imageURL) {image in
                                    image
                                        .resizable()
                                } placeholder: {
                                    ProgressView()
                                }
                            }
                        }
                        .cornerRadius(8.0)
                        .aspectRatio(1, contentMode: .fit)
                        .overlay(alignment: .topTrailing) {
                            Button {
                                if(lazyDeleteImageRequester.requestStatus == .ready) {
                                    lazyDeleteImageRequester.request(imageId: imageId)
                                }
                            } label: {
                                Image(systemName: "xmark.square.fill")
                                    .font(Font.title)
                                    .symbolRenderingMode(.palette)
                                    .foregroundStyle(.white, .red)
                            }
                            .offset(x: 7, y: -7)
                        }
                    }
                }
                .onChange(of: lazyDeleteImageRequester.requestStatus) { oldValue, newValue in
                    if(oldValue == .requesting && newValue == .finish) {
                        withAnimation {
                            imageIdArray.removeAll(where: {$0 == lazyDeleteImageRequester.publishedResult.imageId})
                            lazyDeleteImageRequester.requestStatus = .ready
                        }
                    }
                }
                .padding(.horizontal, 20)
            } else {
                Text("请稍候")
                    .font(.largeTitle)
            }
        }
        .sheet(isPresented: $photoPickerShow) {
            Sell_Picker(imageIdArray: $imageIdArray, bookId: addBookRequest.publishedResult.bookId)
        }
        .navigationTitle("新增出售")
        .navigationBarTitleDisplayMode(.inline)
        .background(addBookRequest.publishedResult.status ? Color(.systemGroupedBackground) : .white)
        .task {
            addBookRequest.request(userId: loginInfo.last?.userId ?? "")
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    modifyBookRequester.request(bookId: addBookRequest.publishedResult.bookId,
                                                bookName: bookNameInput,
                                                tag: bookTagInput,
                                                requirePrice: bookrequirePrice,
                                                author: bookAuthorInput,
                                                course: bookCourseInput,
                                                description: bookDescriptionInput)
                } label: {
                    Text("完成")
                }
                .disabled(bookrequirePrice == "" || bookrequirePrice == "¥" || bookNameInput == "" || bookTagInput == "")
                .foregroundColor(bookrequirePrice == "" || bookrequirePrice == "¥" || bookNameInput == "" || bookTagInput == "" ? .gray : .accent)
            }
        }
        .onChange(of: modifyBookRequester.requestStatus) { oldValue, newValue in
            if(oldValue == .requesting && newValue == .finish) {
                if(modifyBookRequester.publishedResult) {
                    modifyStateRequester.request(bookId: addBookRequest.publishedResult.bookId, state: 1)
                }
            }
        }
        .onChange(of: modifyStateRequester.requestStatus) { oldValue, newValue in
            if(oldValue == .requesting && newValue == .finish) {
                if(modifyStateRequester.publishedResult) {
                    dismiss()
                }
            }
        }
    }
}

#Preview {
    SellNewPage()
}
